<template>
  <div>
    <!-- <el-card> 质量检查 </el-card> -->
    <el-card>
      <div class="list-h">
        <el-form
          :inline="true"
          :model="formInline"
          ref="formRef"
          class="demo-form-inline"
        >
          <!-- <el-col :span="6">
              <el-form-item label="文档编号" prop="billNum">
                <el-input v-model="formInline.billNum" />
              </el-form-item>
            </el-col> -->
          <el-form-item label="文档名称" prop="documentNameLike">
            <el-input v-model="formInline.documentNameLike" />
          </el-form-item>
          <el-form-item label="文档类型" prop="documentTypePathName">
            <el-cascader
              v-model="documentType"
              clearable
              filterable
              :options="documentTypeList"
              :props="documentProp"
              @change="changeType"
              placeholder="输入名称搜索"
            />
          </el-form-item>
          <el-form-item label="创建人" prop="createUserNameLike">
            <el-input v-model="formInline.createUserNameLike" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              class="width-custom230"
              v-model="timeValue"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleChangeDate"
            />
          </el-form-item>
          <el-form-item style="float: right">
            <!-- <el-button
              type="primary"
              @click="handleAdd"
              v-auth="`/document/manage--add`"
              >新增</el-button
            > -->
            <el-button
              style="float: right; margin-left: 10px"
              type="primary"
              @click="handleSearch"
              >查询</el-button
            >
            <el-button style="float: right" @click="handleReset"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-bottom: 10px">
        <el-button
          type="primary"
          @click="handleAdd"
          v-auth="`/document/manage--add`"
          >新增</el-button
        >
        <!-- <el-button
          type="primary"
          @click="handleDownload"
          v-auth="`/document/manage--download`"
          >下载</el-button
        > -->
      </div>
      <el-skeleton
        style="height: calc(100vh - 400px)"
        :rows="8"
        :loading="loading"
        animated
      >
      </el-skeleton>
      <el-table
        :data="tableData"
        :border="true"
        style="width: 100%"
        v-loading="loading"
        v-show="!loading"
        :height="'calc(100vh - 400px)'"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <template #empty>
          <el-empty :image-size="150" description="暂无数据"></el-empty>
        </template>
        <el-table-column type="index" label="序号" width="80">
          <template v-slot="scope">
            <span>{{
              (pageState.pageNum - 1) * pageState.pageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="billNum" label="文档编号" width="200">
        </el-table-column> -->
        <el-table-column prop="documentName" label="文档名称" min-width="200">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="documentTypePathName"
          label="文档类型"
          min-width="200"
        >
        </el-table-column>
        <el-table-column prop="remarks" label="描述" width="200">
        </el-table-column>
        <el-table-column prop="createUserName" label="创建人" width="100">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="{ row }">
            <el-button
              type="text"
              size="small"
              v-auth="`/document/manage--download`"
              @click="downLoadFileClick(row)"
              >下载</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="handleLook(row)"
              v-auth="`/document/manage--look`"
              >查看</el-button
            >
            <!-- <el-button
              type="text"
              size="small"
              @click="handleEdit(row)"
              v-auth="`/document/manage--edit`"
              >编辑</el-button
            > -->
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除该条记录吗？"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button type="text" v-auth="`/document/manage--delete`"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <re-pagination
        v-if="total > 0"
        :total="total"
        v-model:page="pageState.pageNum"
        v-model:limit="pageState.pageSize"
        @pagination="handleChangePage"
      />
    </el-card>
    <Detail
      :showDetailDialog="showDetailDialog"
      :id="detail.id || ''"
      :mode="mode"
      @dialogCallBack="dialogCallBack"
    ></Detail>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
// import { useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";

import RePagination from "/@/components/RePagination/index.vue";
import Detail from "./detail/index.vue";
import * as api from "/@/api/document";
import { downloadFile } from "/@/utils/ecm";
import { storageLocal } from "/@/utils/storage";
const documentProp = ref({
  label: "documentTypeName",
  children: "children",
  value: "documentTypeCode",
  checkStrictly: true
});
const projectInfo = storageLocal.getItem("projectInfo");
const projectManageId = projectInfo?.id || "";

const initData = {
  // TODO 接口未出，后续根据字段直接替换
  billNum: "",
  documentNameLike: "",
  projectNameLike: "", //
  documentTypePathName: "", //
  projectPhaseCode: "", //
  createUserNameLike: "", //
  createTimeStrStart: "", //
  createTimeStrEnd: "" //
};

let timeValue = ref(null);
let documentType = ref(null);

const formInline = reactive(initData);
const pageState = reactive({
  pageNum: 1,
  pageSize: 10
});

const formRef = ref<HTMLFormElement | null>(null) as any;

const tableData = ref([]);
// let projectList = ref([]);
let documentTypeList = ref([]);
let projectPhaseList = ref([]);
let showDetailDialog = ref(false);
let detail = ref({}) as any;
let mode = ref("add");

// const router = useRouter();
let loading = ref<boolean>(false);
let total = ref<number>(0);
const formParams = ref<typeof initData>({ ...initData });

const changeType = value => {
  let str = "";
  value &&
    value.map((el, index) => {
      const docObj = getDocTypeAuth(documentTypeList.value, el);
      const path = index === value.length - 1 ? "" : "/";
      str += docObj.documentTypeName + path;
    });
  formInline.documentTypePathName = str;
};

const getDocTypeAuth = (nodes, searchKey) => {
  for (let _i = 0; _i < nodes.length; _i++) {
    if (nodes[_i].documentTypeCode === searchKey) {
      return nodes[_i];
    } else {
      if (nodes[_i].children && nodes[_i].children.length > 0) {
        const res = getDocTypeAuth(nodes[_i].children, searchKey);
        if (res) {
          return res;
        }
      }
    }
  }
  return null;
};
const getTableList = async (obj: object = {}) => {
  try {
    loading.value = true;
    const { code, data } = await api.fileList({
      ...obj,
      ...pageState,
      moduleType: 1,
      projectManageId
    });
    if (code === 200) {
      tableData.value = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
};

const handleChangeDate = item => {
  console.log(item, "date");
  if (item) {
    formInline.createTimeStrStart = item[0].split(" ")[0];
    formInline.createTimeStrEnd = item[1].split(" ")[0];
  } else {
    formInline.createTimeStrStart = "";
    formInline.createTimeStrEnd = "";
  }
};

const handleReset = () => {
  formRef.value.resetFields();
  documentType.value = null;
  timeValue.value = null;
  handleChangeDate(null);
  formParams.value = initData;
  getTableList(formInline);
};

const handleSearch = () => {
  pageState.pageNum = 1;
  formParams.value = formInline;
  getTableList(formInline);
};

const handleChangePage = () => {
  getTableList(formParams.value);
};

const handleAdd = () => {
  showDetailDialog.value = true;
  detail.value = {};
  mode.value = "add";
};

const dialogCallBack = (bool: any) => {
  showDetailDialog.value = false;
  if (bool) {
    handleSearch();
  }
  console.log(bool);
};

// const handleDownload = () => {
//   router.replace({
//     path: "/projectsA/document/manage/download"
//   });
// };

const handleLook = (row: any) => {
  const item = row.documentAttachmentArr[0];
  window.open(
    `${location.origin}${location.pathname}#/preview?uuidFile=${item.uuidFile}&fileName=${item.fileName}`
  );
  // showDetailDialog.value = true;
  // detail.value = row;
  // mode.value = "look";
  // const { id } = row;
  // router.replace({
  //   path: "/projectsA/document/manage/detail",
  //   query: { id, mode: "look" }
  // });
};

// const handleEdit = row => {
//   showDetailDialog.value = true;
//   detail.value = row;
//   mode.value = "edit";
//   // const { id } = row;
//   // router.replace({
//   //   path: "/projectsA/document/manage/detail",
//   //   query: {
//   //     id,
//   //     mode: "edit"
//   //   }
//   // });
// };

const handleDelete = async row => {
  try {
    const { code, message } = await api.fileDelete({
      id: row.id
    });
    if (code === 200) {
      NotifMessage.success("删除成功");
      getTableList(formParams.value);
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const downLoadFileClick = (row: any) => {
  const { documentAttachmentArr } = row;
  if (documentAttachmentArr && documentAttachmentArr.length > 0) {
    documentAttachmentArr.forEach((val: any) => {
      downloadFile(val.uuidFile, val.fileName);
    });
  } else {
    NotifMessage.error(`当前文档没有文件可以下载`);
  }
};

// 获取项目信息
// const getProjectList = async () => {
//   try {
//     const { code, data } = await postProjectTree({});
//     if (code === 200) {
//       projectList.value = data;
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

// 文档类型
const initDoucumentTypeList = async () => {
  try {
    const { data } = await api.tDocTypeTree({
      type: projectInfo.projectTypeCode === "A" ? "2" : "3"
    });
    documentTypeList.value = data;
  } catch (err) {
    console.log(err);
  }
};

// 项目阶段
const initProjectPhaseList = async () => {
  try {
    const params = {
      dicType: "flow_project_phase"
    };
    const { code, data } = await api.postDictList(params);
    projectPhaseList.value = data;
    console.log(code, data);
  } catch (err) {
    console.log(err);
  }
};

// getProjectList();
initDoucumentTypeList();
initProjectPhaseList();

getTableList(formInline);
</script>
<style scoped lang="scss">
.redColor {
  width: 10px;
  height: 10px;
  background: #f5a623;
  border-radius: 50%;
  display: inline-block;
}
.greenColor {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #21d371;
  display: inline-block;
}
.grayColor {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #979797;
  display: inline-block;
}
</style>
